<?php
#============================
#	customer 客户管理
#	权限控制: 
#   (1) 客户管理
#   (2) 客户审核
#   (3) 用户管理
#   (4) 客户商品推荐
#   (5) 发票管理
#   (6) 收获地址管理
#   (7) 客户导入
#============================
class customerControlPage extends commonControlPage 
{
	/*[(1)客户管理]*/ 
	//opt = add edit view delete
	public function customermanageModule()
	{
		 $opt = in_array($_GET['opt'],array('add','edit','view','delete')) ? $_GET['opt'] : 'view';
		 switch($opt)
		 {
			 case 'view' :  //列表
			 	$this->view->view_act = ' class="active" '; 
			 	$this->GetCustomerList('1');
			 break;
			 case 'add' :   //添加
			 	$this->view->add_act = ' class="active" '; 
				if (POST && AJAX) 
				{
					$data = $this->customerValidate(1);
					$id = customerEntity::Add($data);
					$this->outputJson(1,'保存成功！');
				}
			 break;
			 case 'edit' :  //编辑
				if (POST && AJAX) 
				{
					$data = $this->customerValidate(2);    
					$sum = customerEntity::Update($data);
					$this->outputJson(1,'保存成功！' );
				}
				$cid = (int)$_REQUEST['cid'];
       			$customer = customerEntity::GetRow($cid);
				$this->view->customer = $customer;
			 	$this->view->edit_act = ' class="active" '; 
			 break;
			 case  'delete':  //删除
			 	if(AJAX) 
				{
					$cid = (int)$_GET['cid'];
					$sum = customerEntity::DeteteByID($cid);
					$this->outputJson(1,'操作成功');
				} else {
				$this->outputJson(0,'未知操作');
				}
			 break;
		 }
		 $this->view->opt = $opt;
		 $this->showMainPage('admincp/customer/customer_manage');
	}
	//获得客户列表
	private function GetCustomerList($state='')
	{
        $where = '1';
        $page = (int)$_GET['page_no'];
        $_GET['page_no'] = 'TPT';
        if ('' != $state) {
            $where .= " and `state` = '{$state}'";
        }
		$this->view->customers =  $this->PrePage('customer','customer_id',$where,$page,'customer_id');
    }
	/*客户添加或更新数据验证
	1添加验证 2更新验证*/
    private function customerValidate($add) 
	{
        $data = getRequests(array('customer_id','customer_name','tel','mobile','address','email','mark'));    
        $length = mb_strlen($data['customer_name'],'UTF-8');
        if ($length < 1 || $length > 10) 
		{
           $this->outputJson(0,'客户名称长度应该为1到10位字符','customer_name');
        }
	    if ($add==1) 
		{   //添加
            if (customerEntity::IsExists($data['customer_name'])) 
			{
				$this->outputJson(0,'客户名称已存在','customer_name');
			}
        }
		else
		{  //更新
			if (customerEntity::IsExistsByID($data['customer_name'],$data['customer_id'])) 
			{
				$this->outputJson(0,'客户名称已存在','customer_name');
			}
		}
        if ($data['tel'] && !preg_match('/\d{7}|\d{11}/',$data['tel'])) {
            $this->outputJson(0,'座机号码应为7或11位纯数字，区号和号码间不能有符号','tel');
        }
        if ($data['mobile'] && !preg_match('/\d{11}/',$data['mobile'])) {
            $this->outputJson(0,'手机号码应为11位数字','mobile');
        }
		if($data['email'] && !CheckEmail($data['email']))
		{
			$this->outputJson(0,'邮箱地址格式不正确！','email');
		}
		
        return $data;
    }
	
	/*[(2)客户审核]*/
    public function auditModule() {
        if (POST && AJAX) {
            $cid = $_POST['customer_id'];
            $_ENV['db']->runSql("UPDATE `customer` SET `state` = '1' WHERE `customer_id` = '{$cid}'");
            $this->outputJson(1,'操作成功');
        }
        $this->GetCustomerList('2');
        $this->showMainPage('admincp/customer/customer_audit');
    }
	
	/*[(3)用户管理]*/
	function usermanageModule()
	{
		$opt = in_array($_REQUEST['opt'],array('add','edit','view','delete','set')) ? $_REQUEST['opt'] : 'view';
		$cid = $_GET['customer_id'];
		$uid = $_GET['leader_id'];
		$user = array();
		if($opt=='add' && $cid)
		{  //添加
			$this->view->optname='添加';
			if(AJAX) 
			{
				$data = $this->userValidate(1);
				$data['source'] = '1';
				$id = customerEntity::AddUser($data);
				$this->outputJson(1,"添加成功!");
			}
		}
		else if($opt=='edit' && $uid )
		{  //编辑
			if(AJAX) 
			{
				$data = $this->userValidate(2);
				$data['source'] = '1';
				$id = customerEntity::UpdateUser($data);
				$this->outputJson(1,"更新成功!");
			}
			
			$this->view->optname='修改';
			$user= customerEntity::GetUserRow($uid);
			$cid = $user['customer_id'];
		}
		else if($opt=='delete')
		{  //删除
			if(AJAX) 
			{
            	$uid = (int)$_GET['uid'];
 				$sum = customerEntity::DeteteUserByID($uid);
            	$this->outputJson(1,'操作成功');
        	} else {
            	$this->showMessage('Bad request');
        	}
		}
		else if($opt=='set')
		{
			if(AJAX && POST) 
			{
				$uid = (int)$_POST['node_id'];
                $user =  customerEntity::GetUserRow($uid);
                if (!$user) $this->outputJson(-404,'非法操作');
				$enable= ($user['enable']=='1')?'0':'1';
                $sum = customerEntity::SetUserEnable($uid,$enable);
                $this->outputJson(1,'操作成功','./res/image/'.($enable=='1' ? 'yes' : 'no').'.gif');
			}
		}
		if($cid)
		{
			$this->view->customer = customerEntity::GetRow($cid);
		}
		$this->view->opt = $opt;
		$this->view->user = $user;
		$this->view->users = customerEntity::GetUserList($cid);
		$this->showMainPage('admincp/customer/leader_manage');;
	}
	
	/*用户添加或更新验证
	 1添加验证 2更新验证
	*/
	private function userValidate($add) 
	{
        $data = getRequests(array('leader_id','customer_id','password','username','realname','tel','mobile','address','email','mark','commision'));    
        $length = mb_strlen($data['username'],'UTF-8');
        if ($length < 1 || $length > 10) 
		{
           $this->outputJson(0,'登录名称长度应该为1到10位字符','username');
        }
	    if ($add==1) 
		{   //添加
            if (customerEntity::IsUserExists($data['realname'],$data['username'])) 
			{
				$this->outputJson(0,'用户名称已存在','username');
			}
        }
		else
		{  //更新
			if (customerEntity::IsUserExistsByID($data['realname'],$data['username'],$data['leader_id'])) 
			{
				$this->outputJson(0,'用户名称已存在','username');
			}
		}
		if ($add==2 && !empty($data['password'])) 
		{
            if (!$data['password']) {
                $this->outputJson(0,'密码不能为空','password');
            }
            if ($data['password'] != $_POST['chkpassword']) {
                $this->outputJson(0,'两次输入密码不一致','chkpassword');
            }
        }
        if ($data['tel'] && !preg_match('/\d{7}|\d{11}/',$data['tel'])) {
            $this->outputJson(0,'座机号码应为7或11位纯数字，区号和号码间不能有符号','tel');
        }
        if ($data['mobile'] && !preg_match('/\d{11}/',$data['mobile'])) {
            $this->outputJson(0,'手机号码应为11位数字','mobile');
        }
		if($data['email'] && !CheckEmail($data['email']))
		{
			$this->outputJson(0,'邮箱地址格式不正确！','email');
		}
		if ($data['commision'] && !preg_match('/^(\d|[1-9]\d{0,9})(\.\d{1,2})?$/',$data['commision'] )) {
				$this->outputJson(0,'佣金格式不正确');
			}
        return $data;
    }
	
	
	/*[(4)客户商品推荐]*/
    public function recommendModule() 
	{
        $customer_id = (int)$_GET['customer_id'];
        $customer = $_ENV['db']->fetchCol("SELECT customer_name FROM customer WHERE customer_id = '{$customer_id}'");
        if (!$customer) {
            $this->showMessage('请从客户列表选择客户进行添加','back');
        }
        // 获取当前用户已经推荐过的
        $recommend = $_ENV['db']->fetchAll("SELECT p.product_id,p.name FROM customer_recommend as c LEFT JOIN product as p ON c.product_id=p.product_id WHERE c.customer_id = '{$customer_id}'");
        if (POST && AJAX) 
		{
            $act = $_GET['act'];
            if ($act == 'getlist') 
			{
                $class_id = (int)$_POST['class_id'];
                $keyword = urldecode($_POST['keyword']);
                $nocid = array(0);
                foreach ((array)$recommend as $p) 
				{
                    $nocid[] = $p['product_id'];
                }
                $where = ' where product_id not in ('.implode(',',$nocid).') ';
                if ($class_id) 
				{
                    $class = class_cache::read('product_class');
                    $cid = array($class_id);
                    foreach ((array)$class as $item) {
                        $path = ",{$item['path']},";
                        if (strpos($path,",{$class_id},")) {
                            $cid[] = $item['class_id'];
                        }
                    }
                    $where .= " and cid in (".implode(',',$cid).") ";
                }

                if ($keyword) {
                    $where .= " and name like '%{$keyword}%'";
                }
                $products = $_ENV['db']->fetchAll("SELECT product_id,name FROM product {$where} order by product_id desc");
                $html = '';
                if (!empty($products)) 
				{
                    foreach ($products as $item) {
                        $html .= "<option value='{$item['product_id']}'>{$item['name']}</option>";
                    }
                }
                echo $html;
            } else if($act == 'add') {
                $ids = $_POST['ids'];
                foreach ((array)$ids as $id) {
                    $_ENV['db']->runSql("REPLACE INTO customer_recommend SET `customer_id` = '{$customer_id}',product_id='{$id}'");
                }
            } else if($act == 'remove') {
                $ids = (array)$_POST['ids'];
                $ids[] = 0;
                $_ENV['db']->runSql("DELETE FROM customer_recommend WHERE customer_id = '{$customer_id}' AND product_id IN (".implode(',',$ids).")");
            }
            exit;
        }
        $category = new class_category();
        $product_class = $category->doList('product_class');
        $this->view->recommend = $recommend;
        $this->view->product_class = $product_class;
        $this->showMainPage('admincp/customer/product_recommend');
    }

	/*[(5)发票管理]*/
	public function fapiaoModule() 
	{
        $allow = array('list','modi','add','del');
        $act = in_array($_REQUEST['act'],$allow) ? $_REQUEST['act'] : $allow['0'];
        $cid = (int)$_GET['customer_id'];
        $customer = $_ENV['db']->fetch("SELECT * FROM customer WHERE customer_id = '{$cid}'");
        if (!$customer) {
            $this->showMessage('请从客户列表点击进入操作',AJAX?'0':'back');
        } else {
            $this->view->customer = $customer;
        }
        if ($act == 'modi') {
            $fapiao = $_ENV['db']->fetch("SELECT * FROM fapiao WHERE fid = '".(int)$_GET['fid']."'");
            if (!$fapiao) {
                $this->showMessage('找不到指定的发票信息',AJAX?'0':'back');
            } else {
                $this->view->fapiao = $fapiao;
            }
        }
        if(POST && AJAX) {
            switch($act){
                case 'add':
                    $data = $this->fapiaoValidate();
                    $data['uid'] = $cid;
                    $_ENV['db']->runSql("INSERT INTO fapiao ".$this->buildSql($data));
                    $this->outputJson(1,'操作成功');
                break;
                case 'del':
                    $fid = (int)$_REQUEST['fid'];
                    $_ENV['db']->runSql("DELETE FROM fapiao WHERE fid = '{$fid}'");
                    $this->outputJson(1,'删除成功');
                break;
                case 'modi':
                    $fid = (int)$_REQUEST['fid'];
                    $data = $this->fapiaoValidate();
                    $_ENV['db']->runSql("update fapiao ".$this->buildSql($data)." where fid='{$fid}'");
                    $this->outputJson(1,'操作成功');
                break;
                default:
                    $this->outputJson(0,'非法操作');
                break;
            }
        }
        if ($act == 'modi') {
            $this->showMainPage('admincp/customer_fapiao_modi');
        } else {
            $rows = $_ENV['db']->fetchAll("SELECT * FROM fapiao WHERE `uid` = '{$cid}'");
            $this->view->rows = $rows;
            $this->showMainPage('admincp/customer/fapiao_manager');
        }
    }

	/*[发票添加和更新验证]*/
    private function fapiaoValidate() 
	{
        $data = getRequests(array('name','nr'));
        $data = array_filter($data);
        if (count($data)!=2) {
            $this->outputJson(0,'请补全信息');
        }
        if (mb_strlen($data['name'],'utf-8') > 100) {
            $this->outputJson(0,'发票名称最大100字符');
        }
      	// if (mb_strlen($data['tt'],'utf-8') > 100) {
		//    $this->outputJson(0,'发票抬头最大100字符');
		//  }
        if (mb_strlen($data['nr'],'utf-8') > 100) {
            $this->outputJson(0,'发票内容最大100字符');
        }
        return $data;
    }
    
    /*[(6)收获地址管理]*/
    public function addressModule() {
        $this->view->addScript('cselector');
        $allow = array('list','modi','add','del');
        $act = in_array($_REQUEST['act'],$allow) ? $_REQUEST['act'] : $allow['0'];
        $cid = (int)$_GET['customer_id'];
        $customer = $_ENV['db']->fetch("SELECT * FROM customer WHERE customer_id = '{$cid}'");
        if (!$customer) {
            $this->showMessage('请从客户列表点击进入操作',AJAX?'0':'back');
        } else {
            $this->view->customer = $customer;
        }
        if ($act == 'modi') {
            $cr = $_ENV['db']->fetch("SELECT * FROM customer_receive where cr_id = '".(int)$_REQUEST['cr_id']."'");
            if (!$cr) {
                $this->showMessage('指定的收货地址对象不存在',AJAX?'0':'back');
            } else {
                $this->view->cr = $cr;
            }
        }
        $this->view->act = $act;
        if (POST && AJAX) {
            switch ($act) {
                case 'add':
                    $data = $this->addressValidate();
                    $data['customer_id'] = $cid;
                    $_ENV['db']->runSql("INSERT INTO customer_receive ".$this->buildSql($data));
                    $this->outputJson(1,'操作成功');
                break;
                case 'modi':
                    $data = $this->addressValidate();
                    $_ENV['db']->runSql("update customer_receive ".$this->buildSql($data)." where cr_id = '".(int)$_REQUEST['cr_id']."'");
                    $this->outputJson(1,'操作成功');
                break;
                case 'del':
                    $_ENV['db']->runSql("DELETE FROM customer_receive where cr_id = '".(int)$_POST['cr_id']."'");
                    $this->outputJson(0,'操作成功');
                break;
                default:
                    $this->outputJson(0,'非法操作');
                break;
            }
        }
        $regions = $_ENV['db']->fetchAll("SELECT * FROM region WHERE parent_id = 0");
        $this->view->regions = $regions;
        if ($act == 'modi') {
            //
        } else {
            $rows = $_ENV['db']->fetchAll("SELECT * FROM customer_receive WHERE customer_id = '{$cid}'");
            $this->view->rows = $rows;
        }
        $this->showMainPage('admincp/customer/address_manager');
    }
	
	/*[收获地址添加和更新验证]*/
	private function addressValidate() {
        $data = getRequests(array('receive_name','address','tel','zip'));
        if (count($data) != 4) {
            $this->outputJson(0,'请补全信息');
        }
        if (mb_strlen($data['receive_name'],'utf-8') > 15) {
            $this->outputJson(0,'收货人姓名最大到15字符');
        }
        if (mb_strlen($data['address'],'utf-8') > 200) {
            $this->outputJson(0,'收货地址最大到200字符');
        }
        if (!preg_match('/^[0-9+]{11}$/',$data['tel']) && !preg_match('/^[0-9+]{7}$/',$data['tel'])) {
            $this->outputJson(0,'联系电话应为7或11位纯数字');
        }
        if (!preg_match('/^[0-9+]{6}$/',$data['zip'])) {
            $this->outputJson(0,'邮编应为6位纯数字');
        }
        return $data;
    }
	
	/*[(7)客户导入]*/
	//默认状态正常
    public function importModule() 
    {
    	if (POST) 
        {
        	$file_name = __PATH__.'/tmp/'.uniqid();
        	$upload = new class_upload();
            $upload->setAllowExt('csv');
            $or = $upload->upload('file',$file_name);
            if (!$or) {
                $this->showMessage($upload->getError());
            }

            $file_name .= '.'.$upload->getFileExt();

            $data = file_get_contents($file_name);
            if (!$data) {
                $this->showMessage('系统内部错误');
            }
            $data = explode("\n",$data);
            array_shift($data);
            $data = array_filter($data);

            
            /*[开启事务]*/
			$_ENV['db']->beginTransaction();	
            
            foreach ($data as $item) 
            {
                $item = iconv('gbk','utf-8',$item);
				
				list($id,$n1,$n2,$customer_name,$n3,$address,$created_time,$n4,$tel,$n5,$n6) = explode(',',$item);
				
				if (!$customer_name) {
                	/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->showMessage('编号['.$id.']客户名称不能为空');
                }
				
				if(customerEntity::IsExists($customer_name))
				{
					/*[回滚事务]*/
				 	$_ENV['db']->rollback();
                    $this->showMessage('编号['.$id.']客户名称['.$customer_name.']已存在!');
				}
					
					$resultID = InsertTable('customer',array(
												'customer_name'=>$customer_name,
												'email' => '',
												'address' => $address,
												'tel' => $tel,
												//'mobile' => '',
												//'zip' => '',
												'mark' => '导入',
												'state'=>'1',
												'created_time' => time()
												));
            		if (!$resultID) 
                    {
                       /*[回滚事务]*/
				 		$_ENV['db']->rollback();
                        $this->showMessage('系统异常，导入失败');
                    }
				
                //list($name,$email,$address,$tel,$mobile,$zip,$mark) = explode(',',$item);
//                if (!$name) {
//                	/*[回滚事务]*/
//				 	$_ENV['db']->rollback();
//                    $this->showMessage('客户名称不能为空');
//                }
//	            if (customerEntity::IsExists($name)) 
//				{
//					/*[回滚事务]*/
//				 	$_ENV['db']->rollback();
//					$this->showMessage('客户名称已存在:' . $name);
//				}
//                
//		        if ($tel && !preg_match('/\d{7}|\d{11}/',$tel)) {
//					/*[回滚事务]*/
//				 	$_ENV['db']->rollback();
//		        	$this->showMessage('座机号码应为7或11位纯数字，区号和号码间不能有符号');
//		        }
//		        if ($mobile && !preg_match('/\d{11}/',$mobile)) {
//		        	/*[回滚事务]*/
//				 	$_ENV['db']->rollback();
//		            $this->showMessage('手机号码应为11位数字');
//		        }
//				if($email && !CheckEmail($email))
//				{
//					/*[回滚事务]*/
//				 	$_ENV['db']->rollback();
//					$this->showMessage('邮箱地址格式不正确！');
//				}
//				
//                $_ENV['db']->runSql("INSERT INTO `customer` ".$this->buildSql(array(
//                        'customer_name' => $name,
//                        'email' => $email,
//                        'address' => $address,
//                        'tel' => $tel,
//                        'mobile' => $mobile,
//                        'zip' => $zip,
//                        'mark' => $mark,
//                        'state'=>'1',
//                        'created_time' => time(),
//                    )));
//                    $cid = $_ENV['db']->insertId();
//            		if (!$cid) 
//                    {
//                       /*[回滚事务]*/
//				 		$_ENV['db']->rollback();
//                        $this->showMessage('系统异常，导入失败');
//                    }
            }
            /*[提交事务]*/
			$_ENV['db']->commit();
            $this->showMessage('导入成功');
            @unlink($file_name);
        } 
        else 
        {
            $this->showMainPage("admincp/customer/customer_import");
        
        }
    }
	
	
	/*
	 * 查询客户列表（分页）
	 */
    public function doCustomerList($type='',$state='') 
    {
        $where = '1';
        $page = (int)$_GET['page_no'];
        $_GET['page_no'] = 'TPT';
        if ('' != $type) {
            $where .= " and `type` = '{$type}'";
        }
        if ('' != $state) {
            $where .= " and `state` = '{$state}'";
        }
        $this->view->customers = $this->PrePage('customer','customer_id',$where,$page,'customer_id desc');
    }
	
	/*
	 * 查询客户列表（分页）
	 */
	public function CustomerList($where) 
	{
        $page = (int)$_GET['page_no'];
        $_GET['page_no'] = 'TPT';
        $this->view->customers = $this->PrePage('customer','customer_id',$where,$page,'customer_id desc');
	}
	
	
	
	
	
	/*
	 * 客户注册审核验证
	 */
    public function operauditModule() 
    {
    	$opt = in_array($_GET['opt'],array('view','auth','delete')) ? $_GET['opt'] : 'view';
		switch($opt)
		 {
			 case 'view' :  //列表
			 	$this->view->view_act = ' class="active" '; 
			 	$this->GetAuditLeaderList();
			 break;
			 case  'delete':  //删除
			 	if(AJAX) 
				{
					$cid = (int)$_GET['cid'];
					$sum = customerEntity::DeteteByID($cid);
					$this->outputJson(1,'操作成功');
				} else {
				$this->outputJson(0,'未知操作');
				}
			 break;
			 case 'auth' :  //审核
				if (POST && AJAX) 
				{
					$data = getRequests(array('leader_id','customer_mark','customer_id','enable','mark')); 
					$data['state'] = "1";   //已审核
					$data['enable'] = empty($data['enable'])?'0':'1';
					UpdateTable('customer_leader', saddslashes($data),array('leader_id' => $data['leader_id']));
					$this->outputJson(1,'保存成功！');
				}
				$uid = (int)$_REQUEST['uid'];
       			$leader = customerEntity::GetLeaderRow($uid);
				$this->view->leader = $leader;
				$customers = customerEntity::GetList();
				$this->view->customers = BindComboxs('customer_id','customer_id',$customers,'customer_id','customer_name','');
			 	$this->view->auth_act = ' class="active" '; 
			 break;
		 }
		$this->view->opt = $opt;
		$this->showMainPage('admincp/customer/leader_audit');
    }
	
	
	//获得待审核客户列表
	private function GetAuditLeaderList()
	{
        $where = '1';
        $page = (int)$_GET['page_no'];
        $_GET['page_no'] = 'TPT';
        $where .= " and `source` = 0 and  state=2 ";
		$this->view->leaders =  $this->PrePage('customer_leader','leader_id',$where,$page,'leader_id');
    }
	
	
}